import 'dart:async';
import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hf/widgets/common_w_h_button.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:xr_base/colors.dart';
import 'package:xr_base/dimens.dart';
import 'package:xr_base/image_constants.dart';
import 'package:xr_base/string_constants.dart';
import 'package:xr_base/styles.dart';
import 'package:xr_base/util.dart';
import 'package:xr_base/view_util.dart';
import 'package:xr_image_picker/xr_image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

import '../data/user_data.dart';
import '../models/token.dart';
import '../util/xr_image_cropper_util.dart';

class SetUserInfoPage extends StatefulWidget {
  const SetUserInfoPage({Key? key}) : super(key: key);

  @override
  _SetUserInfoPageState createState() => _SetUserInfoPageState();
}

class _SetUserInfoPageState extends State<SetUserInfoPage> {
  TextEditingController _userNameController = TextEditingController.fromValue(TextEditingValue(
      text: '', selection: TextSelection.fromPosition(TextPosition(affinity: TextAffinity.downstream, offset: 0))));

  final List<SexMo> _sexRadioes = [
    SexMo(
        id: '1',
        title: "男",
        normalIcon: ImageConstants.ico_nan_g,
        selectedIcon: ImageConstants.ico_nan_b,
        normalTextStyle: TextStyles.ts_17_w500_black_160163166,
        selectedTextStyle: TextStyles.ts_17_w500_blue_3E99FC,
        isSelected: false),
    SexMo(
        id: '0',
        title: "女",
        normalIcon: ImageConstants.ico_nv_g,
        selectedIcon: ImageConstants.ico_nv_r,
        normalTextStyle: TextStyles.ts_17_w500_black_160163166,
        selectedTextStyle: TextStyles.ts_17_w500_pink_25291148,
        isSelected: false),
  ];

  List<SheetItem> _avatarItems = [];

  CroppedFile? _tempCroppedFile;

  Token? _token;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: Colors.transparent, // 将状态栏颜色设置为透明
      ),
    );
    _initAvatarItems();
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    final double _distanceFromTop = Dimens.dn_53 - statusBarHeight(context);
    return WillPopScope(
        onWillPop: () async {
          return true;
        },
        child: KeyboardDismissOnTap(
          child: Scaffold(
              resizeToAvoidBottomInset: false,
              backgroundColor: Colours.white_FFFFFF,
              appBar: PreferredSize(
                preferredSize: Size.fromHeight(200),
                child: AppBar(
                  elevation: 0.0,
                  automaticallyImplyLeading: false,
                  // 禁用默认返回按钮
                  backgroundColor: Colors.transparent,
                  // 使AppBar背景透明
                  flexibleSpace: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(Utils.getImgPath(ImageConstants.img_bg_wsxx)),
                        fit: BoxFit.cover, // 图片铺满整个AppBar
                      ),
                    ),
                    child: SafeArea(
                        child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            GestureDetector(
                              onTap: () => Navigator.of(context).pop(),
                              child: Container(
                                margin: EdgeInsets.only(left: Dimens.dn_16, top: _distanceFromTop),
                                child: Icon(Icons.arrow_back),
                              ),
                            ),
                            // Container(
                            //   margin: EdgeInsets.only(right: Dimens.dn_16, top: _distanceFromTop),
                            //   child: GestureDetector(
                            //     onTap: () => {},
                            //     child: Text(
                            //       '跳过',
                            //       style: TextStyle(fontSize: 16),
                            //     ),
                            //   ),
                            // ),
                          ],
                        ),
                        Gaps.getVGap(Dimens.dn_47),
                        Text(
                          'Hi，给自己设置个形象吧～',
                          style: TextStyles.ts_22_w500_000000,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Gaps.getVGap(Dimens.dn_15),
                        Text(
                          '有形象的小伙伴更容易获得关注哦！',
                          style: TextStyles.ts_15_w500_black_160163166,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    )),
                  ),
                ),
              ),
              body: _userInfoBody(context)),
        ));
  }

  _userInfoBody(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: Dimens.dn_38),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _headWidget(context),
            Gaps.getVGap(Dimens.dn_30),
            CommonMaginButton(
              '起个超好听的名字',
              borderRadius: Dimens.dn_25,
              color: Colours.black_000000.withOpacity(0.03),
              height: 60,
              padding: EdgeInsets.symmetric(
                horizontal: Dimens.dn_15,
              ),
              child: TextField(
                  controller: _userNameController,
                  keyboardType: TextInputType.text,
                  style: TextStyles.ts_24_W5OO_010101,
                  inputFormatters: <TextInputFormatter>[
                    LengthLimitingTextInputFormatter(28),
                  ],
                  textAlign: TextAlign.center,
                  decoration: Decorations.ts_18_w500_black_160163166_spacing('起个超好听的名字'),
                  obscureText: false,
                  onChanged: (String? value) {
                    setState(() {});
                  }),
            ),
            Gaps.getVGap(Dimens.dn_30),
            CommonMaginButton(
              '性别',
              borderRadius: Dimens.dn_25,
              color: Colours.black_000000.withOpacity(0.03),
              height: 60,
              padding: EdgeInsets.symmetric(
                horizontal: Dimens.dn_15,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: _sexRadioes.map((SexMo e) {
                  return Flexible(
                    child: InkWell(
                      overlayColor: MaterialStateProperty.resolveWith((states) {
                        return Colors.transparent;
                      }),
                      onTap: () {
                        setState(() {
                          for (SexMo radio in _sexRadioes) {
                            radio.isSelected = false;
                          }
                          e.isSelected = true;
                        });
                      },
                      child: Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              border: Border(
                            right: (e.id == '1')
                                ? BorderSide(color: Colours.black_000000_007, width: 0.5)
                                : BorderSide.none,
                            left: (e.id == '0')
                                ? BorderSide(color: Colours.black_000000_007, width: 0.5)
                                : BorderSide.none,
                          )),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              localImage(
                                e.isSelected ? (e.selectedIcon ?? '') : (e.normalIcon ?? ''),
                                width: Dimens.dn_17,
                                height: Dimens.dn_17,
                              ),
                              Gaps.getHGap(Dimens.dn_8),
                              Text(
                                e.title ?? '',
                                style: e.isSelected ? e.selectedTextStyle : e.normalTextStyle,
                              ),
                            ],
                          )),
                    ),
                    flex: 1,
                  );
                }).toList(),
              ),
              // child: Text("起个超好听的名字", style: TextStyles.ts_18_w500_black_160163166),
            ),
            Gaps.getVGap(Dimens.dn_15),
            Text('注意：注册成功后性别将不可以更改', style: TextStyles.ts_15_w500_010101),
            Gaps.getVGap(Dimens.dn_50),
            CommonWHButton(
              '登录',
              timeout: 2000,
              onTap: _allowNext
                  ? () {
                      _updateUserInfo();
                    }
                  : null,
              width: Dimens.dn_84,
              height: Dimens.dn_84,
              child: localImage(
                _allowNext ? ImageConstants.ico_queding_b : ImageConstants.ico_queding_g,
              ),
            ),
          ],
        ),
      ),
    );
  }

  _headWidget(BuildContext context) {
    return GestureDetector(
      onTap: () {
        _showDialog(context, _avatarItems);
      },
      child: Stack(
        alignment: Alignment.bottomRight,
        children: [
          Container(
            decoration: BoxDecoration(
              color: Colours.gray_239,
              borderRadius: BorderRadius.circular(Dimens.dn_50),
            ),
            child: ObjectUtil.isNotEmpty(_tempCroppedFile)
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(Dimens.dn_50),
                    child: Image.file(
                      File(_tempCroppedFile?.path ?? ''),
                      width: Dimens.dn_100,
                      height: Dimens.dn_100,
                    ),
                  )
                : localImage(ImageConstants.ico_touxiang_g,
                    width: Dimens.dn_100, height: Dimens.dn_100, fit: BoxFit.cover),
          ),
          Positioned(
              child: Container(
            width: Dimens.dn_30,
            height: Dimens.dn_30,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border.all(color: Colours.white_FFFFFF, width: 1),
              // borderSide: BorderSide(width: 2, color: Colours.blue_236AF6),
              color: Colours.blue_CBDFFC,
              borderRadius: BorderRadius.circular(Dimens.dn_15),
            ),
            child: localImage(ImageConstants.ico_xiangji_xiankuang,
                width: Dimens.dn_16, height: Dimens.dn_16, fit: BoxFit.cover),
          ))
        ],
      ),
    );
  }

  _showDialog(BuildContext context, List<SheetItem> items) {
    showCupertinoModalPopup<int>(
        context: context,
        builder: (context) {
          return CupertinoActionSheet(
            cancelButton: CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  Strings.tl_cancel,
                  style: TextStyles.ts_20_666666,
                )),
            actions: items.map((item) {
              return CupertinoActionSheetAction(
                  onPressed: () {
                    Navigator.pop(context);
                    item.voidCallback(context);
                  },
                  child: Text(
                    item.text,
                    style: TextStyles.ts_20_666666,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ));
            }).toList(),
          );
        });
  }

  _initAvatarItems() {
    _avatarItems = [
      SheetItem('照相', (context) async {
        final XFile? _pickedFile = await HiImagePicker.onPickImage(ImageSource.camera, context: context);
        _preUploadImageDao(tempPickedFile: _pickedFile);
      }),
      SheetItem('从相册中选择', (context) async {
        final XFile? _pickedFile = (await HiImagePicker.onPickImage(ImageSource.gallery, context: context));
        _preUploadImageDao(tempPickedFile: _pickedFile);
      }),
    ];
  }

  _preUploadImageDao({XFile? tempPickedFile}) async {
    if (ObjectUtil.isNotEmpty(tempPickedFile)) {
      debugPrint('---😆😆上传文件到七牛, tempPickedFile?.name:${tempPickedFile?.name}😆😆---');

      XrImageCropper.onCropperImage(
              context: context,
              sourcePath: tempPickedFile?.path ?? '',
              aspectRatioLockEnabled: false,
              defaultAspectRatio: true)
          .then((value) {
        if (ObjectUtil.isNotEmpty(value)) {
          setState(() {
            _tempCroppedFile = value;
          });
          _uploadImageDao(croppedFile: value);
        }
      }).catchError((e) {
        showToast('Cropper fail');
      });
    } else {
      /// todo 上传原图
    }
  }

  _loadData() {
    scheduleMicrotask(() {
      UserData().getChannelToken(onOk: (Token token) {
        setState(() {
          _token = token;
        });
      }, onFail: (error) {
        debugPrint('---😆😆获取token异常, error:$error😆😆---');
      });
    });
  }

  _uploadImageDao({CroppedFile? croppedFile}) async {
    if (ObjectUtil.isNotEmpty(_tempCroppedFile) && ObjectUtil.isNotEmpty(_token?.qiniuToken)) {
      UserData().upload(
          token: _token!.qiniuToken!,
          fileName: DateUtil.getNowDateStr(),
          filePath: croppedFile!.path,
          onOk: (String ok) {},
          onFail: (String error) {
            showToast(error);
          });
    }
  }

  _updateUserInfo() {
    try {
      final SexMo? _s = _sexRadioes.firstWhere((element) => element.isSelected, orElse: null);
      if (ObjectUtil.isNotEmpty(_s)) {
        UserData().updateUserInfo(
            nickName: _userNameController.text.trim(),
            sex: _s!.id,
            onOk: (String result) {
              showToast('更新个人信息成功');
            },
            onFail: (String error) {
              showToast(error);
            });
      }
    } catch (e) {}
  }

  bool get _allowNext {
    bool _a = false;
    try {
      final SexMo? _s = _sexRadioes.firstWhere((element) => element.isSelected, orElse: null);
      _a = _s?.isSelected ?? false;
    } catch (e) {
      _a = false;
    }
    return _a;
  }

  // 在页面的dispose方法中恢复状态栏颜色
  @override
  void dispose() {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: Colors.white, // 恢复状态栏颜色为白色
      ),
    );
    _userNameController.dispose();
    _tempCroppedFile = null;
    super.dispose();
  }
}

class SexMo {
  String id;
  String? title;
  String? normalIcon;
  String? selectedIcon;
  TextStyle normalTextStyle;
  TextStyle selectedTextStyle;
  bool isSelected;

  SexMo(
      {required this.id,
      required this.normalTextStyle,
      required this.selectedTextStyle,
      this.title,
      this.normalIcon,
      this.selectedIcon,
      required this.isSelected});
}
